package cn.yunhe.dao;

import cn.yunhe.entity.Member;
import cn.yunhe.entity.Orders;
import cn.yunhe.entity.Product;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
public interface OrderDao {

    @Select("SELECT * FROM orders o ,product p where o.productId = p.id")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "product", javaType = Product.class, one = @One(
                    select = "cn.yunhe.dao.ProductDao.selectById"), column = "productId")})
    List<Orders> findAll();

    @Insert("insert into orders(orderNum,orderTime,peopleCount,orderDesc,payType,orderStatus,productId,memberId) " +
            "values (#{orderNum},#{orderTime},#{peopleCount},#{orderDesc},#{payType},#{orderStatus},#{productId},#{memberId})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insertOrders(Orders orders);

    @Insert("insert into order_traveller values (#{orderId},#{travellerId})")
    void insertOt(@Param("orderId") Integer id, @Param("travellerId") Integer traverID);

    @Delete("delete  from orders where id = #{id}")
    void deleteById(Integer id);

    @Delete("delete  from order_traveller where orderId = #{id}")
    void deleteOtById(Integer id);

    @Select("select  * from orders where id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "product", javaType = Product.class, one = @One(
                    select = "cn.yunhe.dao.ProductDao.selectById", fetchType = FetchType.LAZY), column = "productId")
    })
    Orders selectById(Integer id);

    @Update("update  orders o,product p set orderNum=#{orderNum},orderTime=#{orderTime}," +
            "peopleCount=#{peopleCount},orderDesc=#{orderDesc},payType=#{payType}," +
            "orderStatus=#{orderStatus}" +
            ",p.productName=#{productName},p.productPrice=#{productPrice} " +
            "where o.productId = p.id and o.id =#{id}")
    void updateById(Orders orders);

    @Select("select * from orders where  id = #{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "product", javaType = Product.class, one = @One(
                    select = "cn.yunhe.dao.ProductDao.selectById", fetchType = FetchType.LAZY), column = "productId"),
            @Result(property = "travellers", javaType = List.class, many = @Many(
                    select = "cn.yunhe.dao.TravellerDao.SelectById", fetchType = FetchType.LAZY), column = "id"),
            @Result(property = "member", javaType = Member.class, one = @One(select = "cn.yunhe.dao.MemberDao.selectById", fetchType = FetchType.LAZY), column = "memberId")
    })
    Orders findById(Integer id);
    @Update("update orders o set o.productId = null where o.productId = #{id}")
    void updateProductIdByProductId(Integer id);

}
